package com.example.maybeaccount;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.maybeaccount.Entry.Entrance;
import com.example.maybeaccount.Mode.ClassifyManager;
import com.example.maybeaccount.Mode.DetailsMarkerView;
import com.example.maybeaccount.Mode.Item;
import com.example.maybeaccount.Mode.ItemManager;
import com.example.maybeaccount.Mode.MyPercentFormatter;
import com.example.maybeaccount.Mode.MyTimer;
import com.example.maybeaccount.Mode.SqliteDB;
import com.example.maybeaccount.Mode.StringDateUtils;
import com.example.maybeaccount.datepicker.CustomDatePicker;
import com.example.maybeaccount.datepicker.DateFormatUtils;
import com.example.maybeaccount.multiselectpopupwindows.model.Search;
import com.example.maybeaccount.multiselectpopupwindows.widget.MultiSelectPopupWindows;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.LimitLine.LimitLabelPosition;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
//import com.github.mikephil.charting.formatter.MyPercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Utils;
//import com.xxmassdeveloper.mpchartexample.custom.MyMarkerView;
//import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static android.R.attr.alertDialogTheme;
import static android.R.attr.category;
/** 图表活动，包括一级饼图和单月趋势图 */
public class Chart extends AppCompatActivity implements View.OnClickListener {
    private boolean isTop;
    private LinearLayout linearLayoutProductType;
    private LinearLayout linearLayoutDuration;
    private TabLayout inoutSelector;
    private ImageView options;
    private List<Search> products;
    private MultiSelectPopupWindows productsMultiSelectPopupWindows;
    private int chartType = 0;
    private PieChart mPieChart;
    private LineChart mLineChart;
    private int firstFlag = 0;
    private XAxis lineX;
    private YAxis lineYLeft;
    private YAxis lineYRight;
    private ItemManager itemManager;
    
    private TextView startTime;
    private TextView endTime;
    private TextView textYearAndMonth;

    private CustomDatePicker mTimerPicker1;
    private CustomDatePicker mTimerPicker2;

    public static final int MODE_INCOME = 0;
    public static final int MODE_OUTCOME = 1;
    private int ioMode = 1;

    private int lineChartYear;
    private int lineChartMonth;
    /**
     * 时间段
     */
    private Calendar startCalendar = Calendar.getInstance();
    private Calendar endCalendar = Calendar.getInstance();

    private static final String TAG = "Chart";

    private List<Search> itemlists = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBroadcast();
        setContentView(R.layout.activity_chart);

        startTime = findViewById(R.id.start_time);
        endTime = findViewById(R.id.end_time);
        textYearAndMonth = findViewById(R.id.year_and_month);
        linearLayoutDuration = findViewById(R.id.duration);
        mPieChart = (PieChart) findViewById(R.id.mPieChart);
        mLineChart = (LineChart) findViewById(R.id.lineChart);
        inoutSelector = findViewById(R.id.tablayout);

        initTextYearAndMonth();
        textYearAndMonth.setVisibility(View.INVISIBLE);

        //获取itemManager
        //itemManager = (ItemManager)getIntent().getSerializableExtra("itemManager");
        itemManager = new ItemManager();
        ArrayList<Item> itemArrayList = new ArrayList<Item>();
        itemArrayList = SqliteDB.getInstance(getApplicationContext()).getAllItem();
        if(itemArrayList.size() != 0){
            itemManager.setItem(itemArrayList);
        }
        itemManager.chooseAccount("全部账户");


        ActionBar actionbar=getSupportActionBar();
        if(actionbar!=null){
            actionbar.hide();
        }
        linearLayoutProductType = (LinearLayout) findViewById(R.id.linearLayout_product_type);
        options = findViewById(R.id.option);
        options.setOnClickListener(this);
        getExpendData();



        mPieChart.setVisibility(View.VISIBLE);
        mPieChart.setNoDataText("请先选择要显示的内容");
        mLineChart.setVisibility(View.GONE);
        mLineChart.setNoDataText("请先选择要显示的内容");

        //选择图表类型
        //选择趋势（折线图）
        final TextView textChartRate = findViewById(R.id.chart_rate);
        final TextView textChartTrend = (TextView) findViewById(R.id.chart_trend);
        textChartRate.setTextSize(19);
        textChartTrend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPieChart.setVisibility(View.GONE);
                mLineChart.setVisibility(View.VISIBLE);
                options.setVisibility(View.GONE);
                textChartTrend.setTextSize(19);
                textChartRate.setTextSize(16);
                initLineChart(ioMode);
                textYearAndMonth.setVisibility(View.VISIBLE);
                linearLayoutDuration.setVisibility(View.INVISIBLE);
            }
        });
        //选择比例（饼图）
        textChartRate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPieChart.setVisibility(View.VISIBLE);
                mLineChart.setVisibility(View.GONE);
                options.setVisibility(View.VISIBLE);
                textChartTrend.setTextSize(16);
                textChartRate.setTextSize(19);
                textYearAndMonth.setVisibility(View.INVISIBLE);
                linearLayoutDuration.setVisibility(View.VISIBLE);
            }
        });


        //设置图表时间
        initTimerPicker();
        startTime.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                mTimerPicker1.show(startTime.getText().toString());

            }
        });

        endTime.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                mTimerPicker2.show(endTime.getText().toString());

            }
        });

        //返回按钮
        ImageButton butChartBack = (ImageButton)findViewById(R.id.button_chart_back);
        butChartBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent intent= new Intent(Chart.this, MainActivity.class);
                //startActivity(intent);
                finish();
            }
        });

        //进入成员统计
        TextView textChartMember = findViewById(R.id.chart_member);
        textChartMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent= new Intent(Chart.this, MemberChartActivity.class);
                startActivity(intent);
            }
        });

        //收入支出选择
        inoutSelector.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if(tab.getText().equals("收入")){
                    ioMode = MODE_INCOME;
                    //mLineChart.clear();
                    //mPieChart.clear();
                    getIncomeData();
                    showAllPieData(ioMode);
                    //initLineChart(ioMode);
                    initLineChart(ioMode);
                }
                if(tab.getText().equals("支出")){
                    ioMode = MODE_OUTCOME;
                    //mPieChart.clear();
                    //mLineChart.clear();
                    showAllPieData(ioMode);
                    getExpendData();
                    initLineChart(ioMode);
                    //initPieChart(ioMode);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        showAllPieData(ioMode);

    }


    @Override
    public void onClick(View v) {
        productsMultiSelectPopupWindows = new MultiSelectPopupWindows(this, linearLayoutProductType, 90, products);
        productsMultiSelectPopupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            //获取下拉菜单内容
            @Override
            public void onDismiss() {
                itemlists = productsMultiSelectPopupWindows.getItemList();
                initPieChart(ioMode);
            }
        });
    }
    /**
     * 重写返回键
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            //Intent intent = new Intent(this, MainActivity.class);
            //startActivity(intent);
            finish();
        }
        return true;
    }

    /**
     * 后台唤醒后进入密码界面
     */
    @Override
    protected void onResume(){
        super.onResume();
        isTop = true;
        //int memberFlag = getIntent().getIntExtra("member",0);
        if(firstFlag == 1){
            firstFlag = 0;
            Intent intent = new Intent(Chart.this, Entrance.class);
            intent.putExtra("resume","Chart");
            startActivity(intent);
        }else{
            firstFlag = 0;
        }
    }

    @Override
    protected void onPause(){
        super.onPause();
        isTop = false;
    }

    private void getExpendData() {
        products = new ArrayList<>();
        products.add(new Search("购物", false, "0"));
        products.add(new Search("交通", false, "1"));
        products.add(new Search("餐饮", false, "2"));
        products.add(new Search("娱乐", false, "3"));
        products.add(new Search("医疗", false, "4"));
        products.add(new Search("通讯", false, "5"));
        products.add(new Search("礼物", false, "6"));
    }

    private void getIncomeData() {
        products = new ArrayList<>();
        products.add(new Search("工资", false, "0"));
        products.add(new Search("理财", false, "1"));
        products.add(new Search("奖金", false, "2"));
        products.add(new Search("生活费", false, "3"));
        products.add(new Search("兼职", false, "4"));
        products.add(new Search("礼金", false, "5"));
    }

    private void initPieChart(final int mode){

        mPieChart.setUsePercentValues(true);
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setExtraOffsets(5, 10, 5, 5);
        //标签字体颜色
        mPieChart.setEntryLabelColor(Color.WHITE);
        mPieChart.setEntryLabelTextSize(15f);

        Legend legend = mPieChart.getLegend();
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        legend.setTextSize(12f);
        legend.setFormSize(12f);
        legend.setFormToTextSpace(5f);

//        ArrayList<PieEntry> entryList = new ArrayList<>();
//        entryList.add(new PieEntry(30f, "交通"));
//        entryList.add(new PieEntry(30f, "购物"));
//        entryList.add(new PieEntry(40f, "餐饮"));

        startCalendar = MyTimer.getTimeByString(startTime.getText().toString());
        endCalendar = MyTimer.getTimeByString(endTime.getText().toString());
        final List<PieEntry> entryList = this.getPieEntryList(mode);
        PieDataSet dataSet = new PieDataSet(entryList,"");
        //add color
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.MATERIAL_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.JOYFUL_COLORS) {
            colors.add(c);
        }

        dataSet.setColors(colors);
        dataSet.setDrawIcons(false);
        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);
        //显式格式为百分比
        dataSet.setValueFormatter(new PercentFormatter());

        //** 设置显示数据的属性
        PieData pieData = new PieData(dataSet);
        //pieData.setDrawValues(true);
        pieData.setValueFormatter(new MyPercentFormatter(mPieChart));
        pieData.setValueTextSize(15f);
        pieData.setValueTypeface(Typeface.DEFAULT_BOLD);
        pieData.setValueTextColor(Color.WHITE);

        mPieChart.getDescription().setEnabled(false);
        mPieChart.setData(pieData);
        mPieChart.animateXY(1500,1500);
        mPieChart.invalidate();
        /** 设置点击事件 **/
        mPieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            private String targetValue;
            /** 一次点击，放大 */
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                if (e == null){return;}
                //此时e.getY()等于数据 由此判断点击了哪一个扇区
                for(int i = 0;i < entryList.size(); i++){
                    if(entryList.get(i).getValue() == e.getY()){
                        targetValue = entryList.get(i).getLabel();
                        break;
                    }
                }
            }
            /** 二次点击，显示详情 */
            @Override
            public void onNothingSelected() {
                //图表外部点击事件 也是（上一个方法为点击一次放大） 本方法为二次点击事件
                //Toast.makeText(Chart.this,"点了两次",Toast.LENGTH_LONG).show();
                /** 匹配到底是哪个分类 */
                if(targetValue != null && !targetValue.equals("")){
                    Intent intent = new Intent(Chart.this, ChartClass2Activity.class);
                    intent.putExtra("mode",ioMode);
                    intent.putExtra("startTime",startCalendar);
                    intent.putExtra("endTime",endCalendar);
                    intent.putExtra("nameClass1",targetValue);
                    startActivity(intent);
                }
            }
        });

    }

    private void initLineChart( int mode){
        //基本设置
        startCalendar = MyTimer.getTimeByString(startTime.getText().toString());
        endCalendar = MyTimer.getTimeByString(endTime.getText().toString());
        mLineChart.setDrawBorders(false);
        mLineChart.setBorderColor(Color.LTGRAY);
        mLineChart.setBorderWidth(3f);
        mLineChart.animateX(1000);
        //设置标签位置
        Legend legend = mLineChart.getLegend();
        //legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        legend.setEnabled(false);

        //设置坐标轴
        lineX = mLineChart.getXAxis();
        lineX.setAvoidFirstLastClipping(false);
        lineX.setPosition(XAxis.XAxisPosition.BOTTOM);
        lineX.setDrawGridLines(false);
        //lineX.setDrawLabels(false);


        lineYRight = mLineChart.getAxisRight();
        lineYLeft = mLineChart.getAxisLeft();
        lineYRight.setEnabled(false);
        lineYLeft.setEnabled(false);
        lineYLeft.enableGridDashedLine(10f, 30f, 0f);
        lineYLeft.setAxisMinimum(0f);
        lineYRight.enableGridDashedLine(10f, 30f, 0f);

        //设置数据
        List<Entry> entries = getLineEntryList(mode);
        //一个LineDataSet就是一条线
        LineDataSet lineDataSet = new LineDataSet(entries, null);
        lineDataSet.setLineWidth(1.8f);

        lineDataSet.setColor(Color.parseColor("#5C6FAF"));
        lineDataSet.setCircleColor(Color.parseColor("#5C6FAF"));
        //lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        //lineDataSet.setDrawValues(false);
        LineData data = new LineData(lineDataSet);
        data.setDrawValues(false);
        data.setValueTextSize(15f);

        //设置覆盖物
        DetailsMarkerView detailsMarkerView = new DetailsMarkerView(this);
        detailsMarkerView.setChartView(mLineChart);
        mLineChart.setMarker(detailsMarkerView);

        mLineChart.setScaleYEnabled(false);
        mLineChart.setData(data);
        mLineChart.getDescription().setEnabled(false);
        mLineChart.invalidate();
    }

    /**
     * 获取饼图数据
     * @param mode 设置模式，包括支出和收入
     * @return
     */
    private List<PieEntry> getPieEntryList(int mode){
        ArrayList<String> objectList = new ArrayList<String>();
        //获取自定义内容的字符串数组
        for(Search i : itemlists){
            if(i.isChecked()){
                objectList.add(i.getKeyWord());
            }
        }

        ArrayList<Item> selectedItem = itemManager.getItemByTimeAndClass(objectList, ItemManager.SCREEN_MODE_CLASS1, startCalendar,endCalendar);
        ArrayList<PieEntry> entryList = new ArrayList<PieEntry>();

        if(mode == MODE_INCOME){
            for(Item item:selectedItem){
                entryList.add(new PieEntry((float) item.getIncome(),item.getClass1()));
            }
        }else if(mode == MODE_OUTCOME){
            for(Item item:selectedItem){
                entryList.add(new PieEntry((float) item.getExpend(),item.getClass1()));
            }
        }else{
            Log.d(TAG, "getPieEntryList: mode does not exist!");
        }

        return entryList;
    }

    /**
     * 获取折线图数据
     * @param mode
     * @return
     */
    private List<Entry> getLineEntryList(int mode){
        ArrayList<Entry> entryList = new ArrayList<Entry>();
        ArrayList<Item> selectedItem = new ArrayList<>();
        List<String> formatList = new ArrayList<>();
        int numOfDay = MyTimer.getDayOfMonth(lineChartYear,lineChartMonth);
        if(mode == MODE_INCOME){
            selectedItem = itemManager.getItemOfMonthCountByDay(lineChartYear,lineChartMonth,ItemManager.MODE_INCOME);
            for(int i = 0;i < numOfDay; i++){
                formatList.add((i+1)+"日");
                entryList.add(new Entry(i,(float) selectedItem.get(i).getIncome()));
            }
        }else if(mode == MODE_OUTCOME){
            selectedItem = itemManager.getItemOfMonthCountByDay(lineChartYear,lineChartMonth,ItemManager.MODE_EXPEND);
            for(int i = 0;i < numOfDay; i++){
                formatList.add((i+1)+"日");
                entryList.add(new Entry(i,(float) selectedItem.get(i).getExpend()));
            }
        }
        lineX.setValueFormatter(new IndexAxisValueFormatter(formatList));
        return entryList;
    }

    private void initTimerPicker() {
        String beginTime = "2000-1-1 00:00";
        String stopTime = DateFormatUtils.long2Str(System.currentTimeMillis(), true);

        startTime.setText(beginTime);

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mTimerPicker1 = new CustomDatePicker(Chart.this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                startTime.setText(DateFormatUtils.long2Str(timestamp, true));
                initPieChart(ioMode);
            }
        }, beginTime, stopTime);
        // 允许点击屏幕或物理返回键关闭
        mTimerPicker1.setCancelable(true);
        // 显示时和分
        mTimerPicker1.setCanShowPreciseTime(true);
        // 允许循环滚动
        mTimerPicker1.setScrollLoop(true);
        // 允许滚动动画
        mTimerPicker1.setCanShowAnim(true);

        this.endTime.setText(stopTime);
        String FinalTime = "2030-10-17 18:00";

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mTimerPicker2 = new CustomDatePicker(Chart.this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                endTime.setText(DateFormatUtils.long2Str(timestamp, true));
                initPieChart(ioMode);
            }
        }, beginTime, stopTime);
        // 允许点击屏幕或物理返回键关闭
        mTimerPicker2.setCancelable(true);
        // 显示时和分
        mTimerPicker2.setCanShowPreciseTime(true);
        // 允许循环滚动
        mTimerPicker2.setScrollLoop(true);
        // 允许滚动动画
        mTimerPicker2.setCanShowAnim(true);
    }

    /**
     * 年月选择器
     * @param activity
     */
    private void showYM(final Activity activity) {
        Calendar ca = Calendar.getInstance();
        Calendar caMin = Calendar.getInstance();
        int mYear = ca.get(Calendar.YEAR);
        int mMonth = ca.get(Calendar.MONTH);
        int mDay = ca.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(activity,DatePickerDialog.THEME_HOLO_LIGHT ,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        lineChartMonth = month+1;
                        lineChartYear = year;
                        textYearAndMonth.setText(year+"年"+(month+1)+"月");
                        initLineChart(ioMode);
                    }
                },
                mYear, mMonth, mDay);
        DatePicker datePicker = datePickerDialog.getDatePicker();
        //范围控制,最大能选两年前的月份
        caMin.add(Calendar.YEAR,-20);
        datePicker.setMinDate(caMin.getTimeInMillis());//最小为2年前
        datePicker.setMaxDate(ca.getTimeInMillis());//最大时间为当前年月
        ((ViewGroup) ((ViewGroup) datePicker.getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
        //范围控制
        datePickerDialog.show();
    }

    private void initTextYearAndMonth(){
        Calendar ca = Calendar.getInstance();
        Calendar caMin = Calendar.getInstance();
        int mYear = ca.get(Calendar.YEAR);
        int mMonth = ca.get(Calendar.MONTH)+1;
        lineChartMonth = mMonth;
        lineChartYear = mYear;
        this.textYearAndMonth.setText(mYear+"年"+mMonth+"月");
        //趋势图时间选择
        textYearAndMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showYM(Chart.this);
            }
        });
    }

    private void showAllPieData(int mode){
        if(mode == MODE_INCOME){
            /** 展示所有支出 */
            ClassifyManager classifyManager = new ClassifyManager(this);
            classifyManager.initInFromXML();
            itemlists = classifyManager.getClass1InSearchList();
            initPieChart(ioMode);
        }else if(mode == MODE_OUTCOME){
            /** 展示所有支出 */
            ClassifyManager classifyManager = new ClassifyManager(this);
            classifyManager.initFromXML();
            itemlists = classifyManager.getClass1SearchList();
            initPieChart(ioMode);
        }
    }

    /** 广播监听home和menu */
    class InnerRecevier extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {

                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);

                if (reason != null) {

                    if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY) && isTop) {
                        // "Home键被监听"
                        firstFlag = 1;

                    } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS) && isTop) {
                        //"多任务键被监听"
                        firstFlag = 1;

                    }
                }
            }
        }
    }

    private void initBroadcast(){
        /** 广播 */
        this.getWindow().setFlags(0x80000000,0x80000000);
        //创建广播
        InnerRecevier innerReceiver = new InnerRecevier();
        //动态注册广播
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        //启动广播
        registerReceiver(innerReceiver, intentFilter);
    }
}


